package com.zhouyihe.weblog.common.utils;

import com.zhouyihe.weblog.common.exception.BaseExceptionInterface;
import com.zhouyihe.weblog.common.exception.BizException;
import lombok.Data;

import java.io.Serializable;

/**
 * @author 周益和
 * @ClassName Response
 * @qq 1552951165
 * @date 2024/5/26
 */
@Data
public class Response<T> implements Serializable {
    // 是否成功，默认为 true
    private boolean success = true;
    // 响应消息
    private String message;
    // 异常码
    private String errorCode;
    // 响应数据
    private T data;
    
    // =================================== 成功响应 ===================================
    public static <T> Response<T> success() {
        return new Response<>();
    }
    
    public static <T> Response<T> success(T data) {
        Response<T> response = new Response<>();
        response.setData(data);
        return response;
    }
    
    // =================================== 失败响应 ===================================
    public static <T> Response<T> fail() {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        return response;
    }
    
    public static <T> Response<T> fail(String errorMessage) {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        response.setMessage(errorMessage);
        return response;
    }
    
    public static <T> Response<T> fail(String errorCode, String errorMessage) {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        response.setErrorCode(errorCode);
        response.setMessage(errorMessage);
        return response;
    }
    
    /**
     * 捕获自定义的异常后,根据自定义异常生成失败的响应对象。
     *
     * @param bizException 业务异常对象，包含错误代码和错误消息。
     * @param <T> 响应对象的数据类型。
     * @return 返回一个填充了错误信息的响应对象，标识操作失败。
     */
    public static <T> Response<T> fail(BizException bizException) {
        Response<T> response = new Response<>();
        // 设置响应为失败
        response.setSuccess(false);
        // 设置错误代码
        response.setErrorCode(bizException.getErrorCode());
        // 设置错误消息
        response.setMessage(bizException.getErrorMessage());
        return response;
    }
    
    /**
     * 捕获其他异常后,根据异常返回数据
     * @param baseExceptionInterface
     * @return
     * @param <T>
     */
    public static <T> Response<T> fail(BaseExceptionInterface baseExceptionInterface) {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        response.setErrorCode(baseExceptionInterface.getErrorCode());
        response.setMessage(baseExceptionInterface.getErrorMessage());
        return response;
    }
}
